package com.demo.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * SimpleIOValidateCheck implements IOValidateCheck
 * the class implemet a simple io validate function,include not null check ,simple format check&
 * @author wlgqo
 *
 */
public class SimpleIOValidateCheck implements IOValidateCheck {
	@Override
	public void checkField(Class clazz, Object obj) {
		Field[] fields = clazz.getFields();
		
		if(null == fields)
			return;
		
		for (Field field : fields) {
			IOValidate anno = field.getAnnotation(IOValidate.class);
			if(null == anno)
				continue;
			
			// set value
						String value = anno.value();
						if(null!=value && "".equals(value)){
							try {
								field.set(obj,value);
							} catch (IllegalArgumentException e) {
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							}
						}
			
			//is null check
			boolean bool = anno.isNull();
			if(bool && null==obj){
				throw new IllegalArgumentException(field.getName()+" is null,expect is not null");
			}
			
			
			//format check  
			String format = anno.format();
			if(null!=format && "".equals(format)){
				try {
					Class c = Class.forName(format);
					Method method = c.getMethod("format", null);
					method.invoke(c.newInstance(), null);
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}
			
		}

	}

}
